package com.supply.dl.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.supply.dl.R;
import com.supply.dl.app.AppConfig;
import com.supply.dl.app.http.BaseInfo;
import com.supply.dl.bean.BaseItemBean;
import com.supply.dl.bean.BatchLocationNoticeBean;
import com.supply.dl.bean.InAndOutBoundLocationBean;
import com.supply.dl.bean.MaterielPositionInfoBean;
import com.supply.dl.bean.OperateFlagEnum;
import com.supply.dl.bean.SearchStockBean;
import com.supply.dl.bean.SelectDictionaryBean;
import com.supply.dl.bean.request.ConfirmLocationNoticeDetailRequest;
import com.supply.dl.constant.Constants;
import com.supply.dl.http.HttpManger;
import com.supply.dl.utils.BigDecimalUtil;
import com.supply.dl.utils.CommonNormalAdapterUtil;
import com.supply.dl.utils.InterfaceUtil;
import com.supply.dl.utils.RecyclerViewUtil;
import com.supply.dl.utils.StringUtils;
import com.supply.dl.utils.Utils;
import com.supply.dl.utils.utils.ToastUtil;
import com.supply.dl.view.MaxRecyclerView;
import com.supply.dl.widget.LoadTipFailedLayout;
import com.supply.dl.widget.adapter.CommonNormalAdapter;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;

/**
 * Created by ${qianzhihe} on 2018/5/7.
 * 批量定位界面
 */
public class BatchPositioningActivity extends BaseActivity{

    /**
     * 加载框
     */
    @BindView(R.id.batch_positioning_main_loadView)
    LoadTipFailedLayout loadTipFailedLayout;
    /**
     * 物料列表
     */
    @BindView(R.id.batch_positioning_main_materielRecyclerView)
    MaxRecyclerView materielRecyclerView;
    CommonNormalAdapter materielAdapter;
    int materielAdapterFlag;
    List<BaseItemBean> itemList;

    @BindView(R.id.common_materiel_position_info_showFirstValue)
    TextView showFirstValue;//物料编码
    @BindView(R.id.common_materiel_position_info_showSecondValue)
    TextView showSecondValue;//原料名称
    @BindView(R.id.common_materiel_position_info_showThirdValue)
    TextView showThirdValue;//总数
    @BindView(R.id.common_materiel_position_info_showFourthValue)
    TextView showFourthValue;//未定位数量

    @BindView(R.id.batch_location_content_tvLocationInfo)
    TextView tvLocationInfo;//统一定位信息：未定位 总数量：0件/8.44吨
    @BindView(R.id.batch_location_content_tvShowReservoirPosition)
    TextView tvShowReservoirPosition;//库位
    @BindView(R.id.batch_location_content_tvShowStorehouse)
    TextView tvShowStorehouse;//仓库

    @BindView(R.id.batch_location_content_editShowNumberForPiece)
    EditText editShowNumberForPieceTv;//数量
    @BindView(R.id.batch_location_content_editShowWeightForTon)
    EditText editShowWeightForTonTv;//重量
    @BindView(R.id.batch_location_content_editShowVolumeForSquare)
    EditText editShowVolumeForSquare;//体积

    @BindView(R.id.batch_positioning_main_surePositionLayout)
    LinearLayout surePositionLayout;

    InAndOutBoundLocationBean boundLocationBean;
    MaterielPositionInfoBean materielPositionInfoBean;
    int operateType;

    BatchLocationNoticeBean batchLocationNoticeBean;

    boolean isGetUIMaterielDataEnd=false;
    boolean isGetUIMaterielDataSuccess=false;
    SearchStockBean currentSearchStockBean;//当前选中库位对象
    SelectDictionaryBean currentSelectDictionaryBean;//当前选中仓库对象

    @Override
    protected int getLayoutResource() {
        return R.layout.batch_positioning_main;
    }

    @Override
    protected void initView() {
        super.initView();
        showLeftBack();
        setTitleShow(getResourcesString(R.string.noticeLetterNoBatchPosition));
        editShowNumberForPieceTv.addTextChangedListener(textWatcher);
        editShowWeightForTonTv.addTextChangedListener(textWatcher);
        editShowVolumeForSquare.addTextChangedListener(textWatcher);
    }

    @Override
    protected void initLoadingView() {
        super.initLoadingView();
        loadTipFailedLayout.setRestartOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                batchLocationByNoticeUI();
            }
        });
    }

    @Override
    protected void initListener() {
        super.initListener();
        surePositionLayout.setOnClickListener(this);
        setRightHomeClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finishAllActivityExceptAppointed(MainActivity.class);
            }
        });

        setRightScanClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Utils.startScanActivity(BatchPositioningActivity.this);
            }
        });
        surePositionLayout.setOnClickListener(this);
        tvShowReservoirPosition.setOnClickListener(this);
        tvShowStorehouse.setOnClickListener(this);
        InterfaceUtil.getInstance().setInterfaceCallBackListener(interfacesCallBackListener);
    }

    /**
     * 操作回调
     */
    InterfaceUtil.InterfacesCallBackListener  interfacesCallBackListener=new InterfaceUtil.InterfacesCallBackListener(){
        @Override
        public void onSuccess(BaseInfo<?> baseInfo) {

        }

        @Override
        public void onFailure(String message) {

        }

        @Override
        public void onSuccess(BaseInfo<?> baseInfo, Enum opertateFlagEnum) {
            if (opertateFlagEnum==OperateFlagEnum.BATCH_LOCATION_MATERIEL_DATA){
                isGetUIMaterielDataEnd=true;
                List<MaterielPositionInfoBean> batchLocationNoticeList= (List<MaterielPositionInfoBean>) baseInfo.getData();
                //物料列表数据
                if (batchLocationNoticeList!=null && batchLocationNoticeList.size()>0){
                    isGetUIMaterielDataSuccess=true;
                    for (MaterielPositionInfoBean materielPositionInfoBean: batchLocationNoticeList){
                        itemList.add(new BaseItemBean(materielPositionInfoBean));
                    }
                }else {
                    isGetUIMaterielDataSuccess=false;
                }
            }else if (opertateFlagEnum==OperateFlagEnum.BATCH_LACATION_BASE_DATA){
            }
            if (!isGetUIMaterielDataSuccess){
                checkGetAllDataEnd(true ,"获取数据为空！");
            }else {
                loadTipFailedLayout.setState(LoadTipFailedLayout.STATE_FINISH);
                showMaterielInfo(0);
            }
        }

        @Override
        public void onFailure(String message, Enum opertateFlagEnum) {
            if (opertateFlagEnum==OperateFlagEnum.BATCH_LOCATION_MATERIEL_DATA){
                isGetUIMaterielDataEnd=true;
                isGetUIMaterielDataSuccess=false;
            }else if (opertateFlagEnum==OperateFlagEnum.BATCH_LACATION_BASE_DATA){
            }
            checkGetAllDataEnd(true, message);
        }
    };

    /**
     * 获取物料数据失败或者获取基本数据信息失败时，展示无数据界面
     * @param isShowNoData
     * @param message
     */
    private void checkGetAllDataEnd(boolean isShowNoData , String message){
        if (isShowNoData){
            loadTipFailedLayout.setTextColor(R.color.color_gray);
            loadTipFailedLayout.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
            loadTipFailedLayout.setNormalText(R.string.since_help_load_failed);
            loadTipFailedLayout.setState(LoadTipFailedLayout.STATE_FAILED);
            ToastUtil.showToast(BatchPositioningActivity.this, message);
        }
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        boundLocationBean= (InAndOutBoundLocationBean) getIntent().getSerializableExtra("InAndOutBoundLocationBean");
        materielPositionInfoBean= (MaterielPositionInfoBean) getIntent().getSerializableExtra("MaterielPositionInfoBean");
        operateType=getIntent().getExtras().getInt("operateType");
        itemList=new ArrayList<>();
        materielAdapterFlag=CommonNormalAdapter.FLAG_IN_BOUND_LOCATION_BATCH_MATREIEL_MAIN;
        if (!StringUtils.isEmpty(boundLocationBean.noticeOrderId)){
            setTitleShow(getResourcesString(R.string.notice_letter_batch_location));
        }else {
            setTitleShow(getResourcesString(R.string.order_batch_location));
        }
    }

    @Override
    protected void initRecyclerView() {
        super.initRecyclerView();
        RecyclerViewUtil.initLinearLayoutHorizontal(this, materielRecyclerView);
        materielAdapter= CommonNormalAdapterUtil.initCommonNormalAdapter(R.layout.materiel_position_info_item, itemList, materielAdapterFlag);
        materielAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                showMaterielInfo(position);
            }
        });
        materielRecyclerView.setAdapter(materielAdapter);
    }

    @Override
    protected void onResume() {
        super.onResume();
        batchLocationByNoticeUI();
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        Intent intent = new Intent(this, SelectBaseDataActivity.class);
        String action = "";
        int reqCode = -1;
        switch (v.getId()){
            case R.id.batch_positioning_main_surePositionLayout://确认定位
                if (StringUtils.isEmpty(tvShowReservoirPosition.getText().toString())){
                    ToastUtil.showToast(this, getStringByResId(R.string.toastPleaseSeletedStockPosition));
                    return;
                }
                if (StringUtils.isEmpty(tvShowStorehouse.getText().toString())){
                    ToastUtil.showToast(this, getStringByResId(R.string.toastPleaseSeletedWareHouse));
                    return;
                }
                if (StringUtils.isEmpty(editShowNumberForPieceTv.getText().toString())){
                    ToastUtil.showToast(this, getStringByResId(R.string.toastNumberNotEmpty));
                    return;
                }

                if (Float.parseFloat(editShowNumberForPieceTv.getText().toString())<=0){
                    ToastUtil.showToast(this, getStringByResId(R.string.toastNumberMustMoreThanZero));
                    return;
                }
                if (StringUtils.isEmpty(editShowWeightForTonTv.getText().toString())){
                    ToastUtil.showToast(this, getStringByResId(R.string.toastWeightNotEmpty));
                    return;
                }
                if (Float.parseFloat(editShowWeightForTonTv.getText().toString())<=0){
                    ToastUtil.showToast(this, getStringByResId(R.string.toastWeightMustMoreThanZero));
                    return;
                }
                if (StringUtils.isEmpty(editShowVolumeForSquare.getText().toString())){
                    ToastUtil.showToast(this, getStringByResId(R.string.toastVolumeNotEmpty));
                    return;
                }
                if (Float.parseFloat(editShowVolumeForSquare.getText().toString())<=0){
                    ToastUtil.showToast(this, getStringByResId(R.string.toastVolumeMustMoreThanZero));
                    return;
                }
                batchLocationUIByConfirmLocation();
                break;
            case R.id.batch_location_content_tvShowReservoirPosition://库位
                intent= new Intent(this, DepotSelectActivity.class);
                if (operateType==0){
                    reqCode = AppConfig.BaseDataAction.REQCODE_BATCH_POSITION_IN_BOUND_BY_DEPOT;
                }else {
                    reqCode = AppConfig.BaseDataAction.REQCODE_BATCH_POSITION_OUT_BOUND_BY_DEPOT;
                }
                startActivityForResult(intent, reqCode);
                break;
            case R.id.batch_location_content_tvShowStorehouse://仓库
                //0：入库；1：出库
                if (operateType==0){
                    action = AppConfig.BaseDataAction.WARE_HOUSE_TYPE_0;
                    reqCode = AppConfig.BaseDataAction.REQCODE_BATCH_POSITION_IN_BOUND;
                }else {
                    action = AppConfig.BaseDataAction.WARE_HOUSE_TYPE_1;
                    reqCode = AppConfig.BaseDataAction.REQCODE_BATCH_POSITION_OUT_BOUND;
                }
                intent.putExtra("action", action);
                startActivityForResult(intent, reqCode);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data == null || data.getSerializableExtra("selectBean") == null)
            return;
        switch (requestCode){
            case AppConfig.BaseDataAction.REQCODE_BATCH_POSITION_IN_BOUND://仓库
            case AppConfig.BaseDataAction.REQCODE_BATCH_POSITION_OUT_BOUND:
                currentSelectDictionaryBean = (SelectDictionaryBean) data.getSerializableExtra("selectBean");
                tvShowStorehouse.setText(currentSelectDictionaryBean.getText());
                tvShowStorehouse.setTag(currentSelectDictionaryBean);
                break;
            case AppConfig.BaseDataAction.REQCODE_BATCH_POSITION_IN_BOUND_BY_DEPOT://库位
            case AppConfig.BaseDataAction.REQCODE_BATCH_POSITION_OUT_BOUND_BY_DEPOT:
                currentSearchStockBean= (SearchStockBean) data.getSerializableExtra("selectBean");
                tvShowReservoirPosition.setText(currentSearchStockBean.getStockName());
                tvShowReservoirPosition.setTag(currentSearchStockBean);
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 通知单批量定位数据
     * 获取物料列表数据
     */
    private void batchLocationByNoticeUI(){
        isGetUIMaterielDataEnd=false;
        loadTipFailedLayout.setLoadText(R.string.since_help_loading);
        loadTipFailedLayout.setState(LoadTipFailedLayout.STATE_PROGRESS);
        if (!StringUtils.isEmpty(boundLocationBean.noticeOrderId)){//通知单ID非空时
            InterfaceUtil.getInstance().batchLocationNoticeUIByNoticeOrderId(getStringByIsEmpty(boundLocationBean.noticeOrderId), OperateFlagEnum.BATCH_LOCATION_MATERIEL_DATA, this);
        }else {//通知单ID为空时
            InterfaceUtil.getInstance().batchLocationNoticeUIByOrderId(getStringByIsEmpty(boundLocationBean.orderId), OperateFlagEnum.BATCH_LOCATION_MATERIEL_DATA, this);
        }
    }

    /**
     * 确认定位事件
     */
    private void batchLocationUIByConfirmLocation(){
        ConfirmLocationNoticeDetailRequest confirmLocationNoticeDetailRequest =new ConfirmLocationNoticeDetailRequest();
        confirmLocationNoticeDetailRequest.orderId=getStringByIsEmpty(boundLocationBean.orderId);
        confirmLocationNoticeDetailRequest.orderNo=getStringByIsEmpty(boundLocationBean.orderNo);
        confirmLocationNoticeDetailRequest.noticeOrderId=getStringByIsEmpty(boundLocationBean.noticeOrderId);
        confirmLocationNoticeDetailRequest.noticeOrderNo=getStringByIsEmpty(boundLocationBean.noticeOrderNo);
        //从选中的物料对象中获取
        confirmLocationNoticeDetailRequest.orderDetailId=getStringByIsEmpty(materielPositionInfoBean.orderDetailId);
        confirmLocationNoticeDetailRequest.noticeOrderDetailId=getStringByIsEmpty(materielPositionInfoBean.noticeOrderDetailId);
        //库位、仓库数据
        confirmLocationNoticeDetailRequest.whId=getStringByIsEmpty(currentSelectDictionaryBean.getValue());//仓库id
        confirmLocationNoticeDetailRequest.stockId=getStringByIsEmpty(currentSearchStockBean.getStockId());//库位id
        confirmLocationNoticeDetailRequest.invId=getStringByIsEmpty(currentSearchStockBean.getId());//库存id

        confirmLocationNoticeDetailRequest.skuId=getStringByIsEmpty(materielPositionInfoBean.skuId);
        confirmLocationNoticeDetailRequest.skuCode=getStringByIsEmpty(materielPositionInfoBean.skuCode);
        confirmLocationNoticeDetailRequest.skuName=getStringByIsEmpty(materielPositionInfoBean.skuName);

        confirmLocationNoticeDetailRequest.amount=BigDecimalUtil.getBigDecimalByString(editShowNumberForPieceTv.getText().toString());
        confirmLocationNoticeDetailRequest.weight=BigDecimalUtil.getBigDecimalByString(editShowWeightForTonTv.getText().toString());
        confirmLocationNoticeDetailRequest.volume=BigDecimalUtil.getBigDecimalByString(editShowVolumeForSquare.getText().toString());
        //操作类型：0：入库、1：出库
        confirmLocationNoticeDetailRequest.operateType=operateType;
        if (!StringUtils.isEmpty(boundLocationBean.noticeOrderId)){//通知单ID非空时，调用2.9接口
            InterfaceUtil.getInstance().batchLocationUIConfirmLocationByNoticeOrderId(confirmLocationNoticeDetailRequest, this);
        }else {//通知单ID为空时，调用2.16接口
            InterfaceUtil.getInstance().batchLocationUIConfirmLocationByOrderId(confirmLocationNoticeDetailRequest, this);
        }

    }

    /**
     * 数据获取回调
     * @param baseInfo
     */
    @Override
    public void onSuccess(BaseInfo<?> baseInfo) {
        super.onSuccess(baseInfo);
    }

    @Override
    public void onFailure(String message) {
        super.onFailure(message);
    }

    /**
     * 展示当前物料数据信息
     * @param currentPosition
     */
    private void showMaterielInfo(int currentPosition){
        if (itemList.size()<=0){
            return;
        }
        MaterielPositionInfoBean materielPositionInfoBean= (MaterielPositionInfoBean) itemList.get(currentPosition).object;
        if (materielPositionInfoBean!=null){
            showFirstValue.setText(materielPositionInfoBean.skuCode);
            showSecondValue.setText(materielPositionInfoBean.skuName);
            showThirdValue.setText(materielPositionInfoBean.detailAmount+"件/"+materielPositionInfoBean.detailWeight+"吨");
            showFourthValue.setText(materielPositionInfoBean.notPositionAmount+"件/"+materielPositionInfoBean.notPositionWeight+"吨");
            tvLocationInfo.setText("未定位 总数量："+materielPositionInfoBean.detailAmount+"件/"+materielPositionInfoBean.detailWeight+"吨");
            String numberString=batchLocationNoticeBean==null ? "0" : String.valueOf(batchLocationNoticeBean.detailAmount);
            editShowNumberForPieceTv.setText(numberString);
            String weightString=batchLocationNoticeBean==null ? "0" : String.valueOf(batchLocationNoticeBean.detailWeight);
            editShowWeightForTonTv.setText(weightString);
            String volumeString=batchLocationNoticeBean==null ? "0" : String.valueOf(batchLocationNoticeBean.detailVolume);
            editShowNumberForPieceTv.setText(volumeString);
        }

        for (BaseItemBean baseItemBean : itemList){
            ((MaterielPositionInfoBean)baseItemBean.object).isSelected=false;
        }
        ((MaterielPositionInfoBean) itemList.get(currentPosition).object).isSelected=true;
        materielAdapter.setNewData(itemList);
    }

    TextWatcher textWatcher=new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };

}
